package com.st.handler;

import cn.hutool.json.JSONUtil;
import com.st.common.util.ResponseE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shent
 */
@Slf4j
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        UserDetails userDetails = (UserDetails) token.getPrincipal();
        logWrite(userDetails);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "application/json");
        response.setHeader("Access-Control-Expose-Headers", "Auth-Token");
        response.getWriter().print(JSONUtil.toJsonStr(ResponseE.ok(null, "login_successfully")));
    }

    private void logWrite(UserDetails userDetails) {
        // todo 记录登录系统日志
    }
}
